#include "httpServer.hpp"
#include <memory>

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " serverport" << endl;
}

//TODO: 1.根据请求资源后缀确定content-type 2.get和post请求对比(get输入的内容填充到url中用?隔开 post输入的内容填充到请求正文)
void Get(httpRequest& in, httpResponse* out)
{
    cout << "---------- http request start ----------" << endl;
    cout << in.inbuffer << endl;
    cout << "method: " << in.method << endl;
    cout << "url: " << in.url << endl;
    cout << "version: " << in.version << endl; 
    cout << "path: " << in.path << endl;
    cout << "suffix: " << in.suffix << endl;
    cout << "size: " << in.size << endl;
    cout << "---------- http request end ----------" << endl;
    
    string resline = "HTTP/1.1 200 OK\r\n";
    //string resline = "HTTP/1.1 302 redirect\r\n";
    string resheader = "Content-Type: ";
    resheader += suffixToType(in.suffix);
    resheader += "\r\n";
    if (in.size > 0)
    {
        resheader += "Content-Length: ";
        resheader += to_string(in.size);
        resheader += "\r\n";
    }
    //resheader += "Location: https://www.qq.com/\r\n";//重定向
    string resblank = "\r\n";
    //请求固定内容
    //string resbody = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>北京交通广播《一路畅通》“交通大家谈”节目，特邀北京市交通委员会地面公交运营管理处处长赵震、北京市公安局公安交通管理局秩序处副处长 林志勇、北京交通发展研究院交通规划所所长 刘雪杰为您解答公交车专用道6月1日起社会车辆进出公交车道须注意哪些？</p></body></html>";
    //请求指定文件
    string resbody;
    resbody.resize(in.size + 1);
    if (!readFile(in.path, (char*)resbody.c_str(), in.size))//资源文件不存在
    {
        struct stat st;
        stat(html_404.c_str(), &st);
        string body;
        body.resize(st.st_size + 1);
        readFile(html_404, (char*)body.c_str(), st.st_size);//将404网页返回给客户端
        resbody = body;
    }
    out->outbuffer += resline;
    out->outbuffer += resheader;
    out->outbuffer += resblank;
    cout << "---------- http response start ----------" << endl;
    cout << out->outbuffer << endl;
    cout << "---------- http response end ----------" << endl;
    out->outbuffer += resbody;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    int16_t port = stoi(argv[1]);
    unique_ptr<httpServer> hsvr(new httpServer(port));
    hsvr->initServer();
    hsvr->startServer(Get);
    return 0;
}

